package org.beetl.sql.mapper.identity;

import org.beetl.sql.annotation.builder.Builder;
import org.beetl.sql.annotation.entity.Table;
import org.beetl.sql.clazz.kit.BeanKit;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.SqlId;
import org.beetl.sql.mapper.builder.MethodParamsHolder;

import java.beans.PropertyDescriptor;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author xiandafu
 */
public class UpdateRMI extends BaseRMI {

	Class targetType;
	public UpdateRMI(SqlId sqlId, MethodParamsHolder holder) {
		super(sqlId, holder);
	}

	@Override
	public Object call(SQLManager sm, Class entityClass,  Method m, Object[] args) {
		ArrayList<String> customMethodList = new ArrayList<>();
		customMethodList.add("customizeInsert");
		customMethodList.add("customizeUpdateById");
		customMethodList.add("customizeTemplateById");

		// 包含自定义方法
		if (customMethodList.contains(m.getName())) {
			// 包含加密注解标识
			Boolean flag = false;
			try {
				if (Objects.nonNull(args) && args.length > 0 && Objects.nonNull(entityClass) && entityClass.isAnnotationPresent(Table.class)) {
					PropertyDescriptor[] ps = BeanKit.propertyDescriptors(entityClass);
					for (PropertyDescriptor p : ps) {
						List<Annotation> attrAns = BeanKit.getAllAnnotation(entityClass, p.getName());
						for (Annotation an : attrAns) {
							Builder builder = an.annotationType().getAnnotation(Builder.class);
							if (Objects.nonNull(builder)) {
								flag = true;
							}
						}
					}
				}
			} catch (Exception e) {
				// ignore
			}
			if (flag) {
				return sm.update(this.sqlId, args[0]);
			}
		}
		int ret = sm.update(sqlId, this.getParas(args));
		return ret;
	}
}
